# -*- coding: utf-8 -*-
def create_db(db, name):
	try:
		# 数据库连接
		
		# 创建游标，通过连接与数据通信
		cursor = db.cursor()
		# 执行sql语句
		cursor.execute('show databases')
		rows = cursor.fetchall()
		for row in rows:
			tmp = list(row)[0]
			#判断数据库是否存在
			if name == tmp:
				print "database is exists"
				cursor.execute('drop database if exists ' + name)
		cursor.execute('create database ' + name)
		# 提交到数据库执行
		db.commit()
		
	except MySQLdb.Error, e:
		print "Mysql Error %d: %s" % (e.args[0], e.args[1])
		raise e
def run_struct(db,file_name):
	file = open(file_name)
	content = file.read()
	content = content.split(";")
	try:
		cursor = db.cursor()
		for line in content:
			print line 
			cursor.execute(line)
			db.commit()
	except Exception, e:
		print "Mysql Error %d: %s" % (e.args[0], e.args[1])
	


def start(mysql_host,database,username,password):
	import MySQLdb
	try:
		db = MySQLdb.connect(mysql_host,username, password, charset='utf8')
	except Exception, e:
		return "数据库连接失败！"
	
	print "create database..."
	create_db(db,database)
	db.close()

	db = MySQLdb.connect(mysql_host, username, password,database,charset='utf8')
	#创建表结构
	print "create_struct ..."
	run_struct(db,"item_data.sql")
	return "创建完毕"
